import React, { useState, useEffect, useCallback } from 'react';
import { getSysDepartmentFindList, getSysUserSelected } from '../../../../../../Api/listUrl';
import { postAccAmoebaCostUpdateAccAmoebaCost, getAccAmoebaCostUpdateShow, putAccAmoebaCostInsertAccAmoebaCost } from '../../../../financialApi';
import {
    ArtificialStatus
} from '../../../enum'
import { Modal, Form, Select, Row, Col, message, Button, DatePicker, Input } from 'antd';
import { All } from './style'
import moment from 'moment';
import { MinusCircleOutlined } from '@ant-design/icons';
const { Option } = Select;

const FillInModule = ({ clickId, setFillInModuleShow, FillInModuleShow, setClickId, listFun }) => {
    const [form] = Form.useForm();
    const { validateFields, resetFields, setFieldsValue } = form;
    const [buttonLoading, setButtonLoading] = useState(false);
    const [departmentList, setDepartmentList] = useState([]); //领用部门
    const [userList, setUserList] = useState([]);  //人员
    const departmentFun = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getSysDepartmentFindList();
                if (code === '20000') {
                    setDepartmentList(data);
                } else {
                    message.error(msg);
                }
            })();
        },
        [],
    )
    const userFun = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getSysUserSelected();
                if (code === '20000') {
                    setUserList(data);
                } else {
                    message.error(msg);
                }
            })();
        },
        [],
    )
    useEffect(() => {
        departmentFun();
        userFun();
        if (clickId) {
            ; (async () => {
                const { code, msg, data } = await getAccAmoebaCostUpdateShow({ costId: clickId });
                if (code === '20000') {
                    data.grantDate = moment(data.grantDate);
                    data.costDetails.forEach((element, index) => {
                        data.costDetails[index].shareDate = moment(element.shareDate);
                    });
                    setFieldsValue(data)
                } else {
                    message.error(msg);
                }
            })()
        }
    }, [departmentFun, userFun, clickId, setFieldsValue])
    const handleOk = () => {
        validateFields().then(values => {
            console.log(values)
            let trueFalse = true;
            if (values.costDetails.length <= 0) {
                message.error('请输入分担明细');
                return
            } else {
                // 1398082618501173250
                values.costDetails.forEach(element => {
                    if (element.shareDep === '1398082618501173250' && !element.shareUser) {
                        message.error('营销中心部门需要填写承担人员');
                        trueFalse =false;
                        return
                    }
                });
            }
            if(trueFalse) {
                values.grantDate = moment(values.grantDate).format("YYYY-MM-DD");
                values.costDetails.forEach((element, index) => {
                    values.costDetails[index].shareDate = moment(element.shareDate).format("YYYY-MM");
                });
                setButtonLoading(true);
                if (clickId) {
                    values.id = clickId;
                    ; (async () => {
                        const { code, msg } = await postAccAmoebaCostUpdateAccAmoebaCost(values);
                        if (code === '20000') {
                            message.success('编辑成功！');
                            setClickId(undefined);
                            listFun();
                            resetFields();
                            setButtonLoading(false);
                            setFillInModuleShow(false);
                        } else {
                            message.error(msg);
                        }
                    })();
                } else {
                    ; (async () => {
                        const { code, msg } = await putAccAmoebaCostInsertAccAmoebaCost(values);
                        if (code === '20000') {
                            message.success('添加成功！');
                            listFun();
                            resetFields();
                            setButtonLoading(false);
                            setFillInModuleShow(false);
                        } else {
                            message.error(msg);
                        }
                    })();
                }
            }


        })

    };

    const handleCancel = () => {
        setClickId(undefined);
        resetFields();
        setButtonLoading(false);
        setFillInModuleShow(false);
    };
    return (<Modal
        width={800}
        title={clickId ? "编辑填报" : "填报"}
        visible={FillInModuleShow}
        onCancel={handleCancel}
        bodyStyle={{ padding: '25px 63px' }}
        footer={[
            <Button style={{
                width: '88px',
                height: '34px',
            }} key="back" onClick={handleCancel}>
                取消
            </Button>,
            <Button key="submit" style={{
                width: '88px',
                height: '34px',
            }} type="primary" loading={buttonLoading} onClick={handleOk}>
                确定
            </Button>
        ]}
    >

        <Form form={form}><All >
            <Row>
                <Col span={24} style={{ marginBottom: '19px' }}>
                    <span className="icon iconfont" style={{ marginRight: '10px' }}>&#xe616;</span>
                    <span style={{
                        fontSize: '16px',
                        fontFamily: 'PingFang SC',
                        fontWeight: 'bold',
                        color: '#333333'
                    }}>基本信息</span>
                </Col>
                <Col span={12}>
                    <Form.Item
                        label="人工类别"
                        name="artType"
                        wrapperCol={{ span: 15 }}
                        rules={[
                            {
                                required: true,
                                message: '请选择人工类别!',
                            },
                        ]}
                    >
                        <Select placeholder='请选择'>
                            {
                                ArtificialStatus.map((item, index) => <Option value={index} key={item + index}>{item}</Option>)
                            }
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        label="发放时间"
                        name="grantDate"
                        wrapperCol={{ span: 15 }}
                        rules={[
                            {
                                required: true,
                                message: '请选择发放时间!',
                            },
                        ]}
                    >
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item
                        label="发放总额"
                        name="grantAmount"
                        wrapperCol={{ span: 15 }}
                        rules={[
                            {
                                required: true,
                                message: '请输入成本金额!',
                            },
                            {
                                required: true,
                                pattern: new RegExp(/^[0-9]+(.?[0-9]{1,2})?$/, "g"),
                                message: '请输入正确的成本金额'
                            },
                        ]}
                    >
                        <Input suffix="元" />
                    </Form.Item>
                </Col>
            </Row>
            <Row>
                <Col span={24} style={{ marginBottom: '19px' }}>
                    <span className="icon iconfont" style={{ marginRight: '10px' }}>&#xe673;</span>
                    <span style={{
                        fontSize: '16px',
                        fontFamily: 'PingFang SC',
                        fontWeight: 'bold',
                        color: '#333333'
                    }}>分摊明细</span>
                </Col>
                <Form.List name="costDetails" initialValue={[]}>
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, fieldKey, ...restField }) => (
                                <Row key={key} style={{
                                    borderBottom: '1px solid #F4F4F4',
                                    marginBottom: '20px'
                                }}>
                                    <Col span={12}>
                                        <Form.Item
                                            {...restField}
                                            label='日期'
                                            wrapperCol={{ span: 15 }}
                                            name={[name, 'shareDate']}
                                            fieldKey={[fieldKey, 'shareDate']}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请选择分摊日期!',
                                                },
                                            ]}
                                        >
                                            <DatePicker style={{ width: '100%' }} picker="month" />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            {...restField}
                                            label='部门'
                                            name={[name, 'shareDep']}
                                            fieldKey={[fieldKey, 'shareDep']}
                                            wrapperCol={{ span: 15 }}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请选择分摊部门！',
                                                }
                                            ]}
                                        >
                                            <Select placeholder='请选择'>
                                                {
                                                    departmentList.map((item, index) => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                                }
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            {...restField}
                                            label="人员"
                                            name={[name, 'shareUser']}
                                            fieldKey={[fieldKey, 'shareUser']}
                                            labelCol={{ span: 6, offset: 0 }}
                                            wrapperCol={{ span: 15, offset: 0 }}
                                        // rules={[
                                        //     {
                                        //         required: true,
                                        //         message: '请选择分摊人员!',
                                        //     },
                                        // ]}
                                        >
                                            <Select style={{ width: '100%' }} placeholder='请选择'>
                                                {
                                                    userList.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)
                                                }
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item
                                            {...restField}
                                            label="分摊额"
                                            name={[name, 'shareMoney']}
                                            fieldKey={[fieldKey, 'shareMoney']}
                                            wrapperCol={{ span: 15 }}
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入分摊金额!',
                                                },
                                                {
                                                    required: true,
                                                    pattern: new RegExp(/^[1-9]\d*$/, "g"),
                                                    message: '请输入正确的分摊金额'
                                                },
                                            ]}
                                        >
                                            <Input suffix="元" />
                                        </Form.Item>
                                    </Col>
                                    <MinusCircleOutlined style={{
                                        position: 'absolute',
                                        right: '60px',
                                        lineHeight: '35px'
                                    }} onClick={() => remove(name)} />
                                </Row>
                            ))}
                            <Form.Item style={{
                                position: 'absolute',
                                right: '40px'
                            }}>
                                <Button style={{
                                    fontSize: '14px',
                                    fontFamily: 'PingFang SC',
                                    fontWeight: 'bold',
                                    color: '#1890FF'
                                }} type="link" onClick={() => add()} block icon={<span className="iconfont">&#xeaf3;</span>}>
                                    添加一组
                                </Button>
                            </Form.Item>
                        </>
                    )}
                </Form.List>

            </Row>
        </All>
        </Form>
    </Modal>)
}

export default FillInModule;